package cn.js.controller;

import cn.js.common.R;
import cn.js.domain.User;
import cn.js.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    public R login(@RequestBody User user) {
        Map<String, Object> map = userService.login(user);
        if (!map.get("token").equals("") && !map.get("username").equals("")) {
            return R.ok().message("登陆成功").data("token", map);
        }
        return R.error().message("登陆失败");
    }


    /**
     * 用户退出
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/logOut")
    public R logout(HttpServletRequest request, HttpServletResponse response) {
        //获取token
        String token = request.getParameter("Authorization");
        //如果没有从头部获取token，那么从参数里面获取
        if (ObjectUtils.isEmpty(token)) {
            token = request.getHeader("Authorization");
        }
        //获取用户相关信息
        Authentication authentication
                = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
        //清空用户信息
            new SecurityContextLogoutHandler().logout(request,
                    response, authentication);
        //清空redis里面的token
            String key = "token_" + token;
            stringRedisTemplate.delete(key);
        }
        return R.ok().message("用户退出成功");
    }
}
